import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import EditTemplate from '@/components/EditTemplate';
import { Table, Card, Row, Button, Modal, Input, message } from 'antd';
import { timeFormat } from '@/utils/common';
import AuthButton from '@/components/AuthButton';
import Status from '@/pages/components/Status';
import CapitalSource from '@/pages/components/capitalSource';
import { eventBus } from '@/utils/event';
import MoneyTable from './table';
const { TextArea } = Input;

const BuildEdit = ({ location, dispatch, uuid, update, dict }: any) => {
  const [detail, setDetail] = useState(null);
  const { id, readOnly, isApprove = false, fromType = 7 } = location.query;
  const [showModal, setshowModal] = useState(false);
  const pointType = { 3: 'PLAN', 1: 'ANNUAL', 7: 'MONEY' }[fromType];
  const [comment, setcomment] = useState('');
  const saveUrl = id ? '/api/budget/v1/update' : '/api/budget/v1/create';
  const [filters, setFilter]: any = useState([]);
  const tabChange = tab => {
    console.log('tab:', tab);
    tab == 1 ? setFilter(filters1) : setFilter(filters2);
  };
  useEffect(() => {
    if (id) {
      if (update === false) return;
      dispatch({
        type: '$request/post',
        payload: {
          url: '/api/budget/v1/detail',
          data: {
            uuid: uuid || id,
            page: 0,
            size: 10,
          },
        },
      }).then(res => {
        console.log('储备项目申报详情：', res);
        res.project.buildType !== 'BUILD'
          ? setFilter(filters3)
          : setFilter(filters1);
        setDetail({
          ...res,
          ...res.project,
          uuid: res.uuid,
          createTime: timeFormat(res.createTime),
          fundSource: res.budget,
          buildType: res.project.buildType == 'BUILD' ? '建设' : '保障',
        });
        projectUuid = res.project.uuid;
        yearSelect(res.budgetYear);
      });
    } else {
      setFilter(filters1);
    }
  }, []);
  const projectChange = (uuid, data) => {
    if (update === false) return;
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/budget/v1/project/query',
        data: { uuid },
      },
    }).then(list => {
      const res = list.find(item => item.uuid == uuid);
      res.createTime = timeFormat(new Date(), 'YYYY-MM-DD');
      res.no = [res.no, res.code].toString();
      res.buildType !== 'BUILD' ? setFilter(filters3) : setFilter(filters1);
      res.buildType = res.buildType == 'BUILD' ? '建设' : '保障';
      setDetail({ ...res });
      projectUuid = res.uuid;
      eventBus.$emit('budge-detail', {});
    });
  };
  let projectUuid = null;
  const yearSelect = year => {
    console.log(year);

    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/budget/v1/last',
        data: {
          projectUuid: projectUuid,
          year: year,
        },
      },
    }).then(res => {
      eventBus.$emit('budge-detail', res);
    });
  };

  const filters1 = [
    {
      title: '基础信息',
      list: [
        {
          key: id ? 'name' : 'projectUuid',
          type: id ? 'text' : 'select',
          label: '项目名称',
          asyncopt: {
            url: '/api/budget/v1/project/query',
          },
          prop: {
            onChange: (uuid, data) => {
              console.log('uuid', uuid);
              projectChange(uuid, data);
            },
          },
          span: 12,
        },
        {
          key: 'no',
          type: 'text',
          label: '项目ID(代码)',
          placeholder: '请输入姓名',
          span: 12,
        },
        {
          key: ['ownerOrgUnit', 'name'],
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'buildType',
          type: 'text',
          label: '项目性质',
          span: 12,
        },
        {
          key: 'projectType',
          type: 'tabs',
          prop: {
            defaultActiveKey: '1',
            onChange: tabChange,
          },
          options: [
            {
              label: '预算填报',
              value: 1,
            },
            {
              label: '基本信息',
              value: 2,
            },
          ],
          span: 24,
        },
        {
          key: 'budgetYear',
          type: 'select',
          label: '预算年份',
          options: dict.yearList,
          prop: {
            onChange: yearSelect,
          },
          span: 12,
        },
      ],
    },
    {
      title: '上年资金使用情况',
      list: [
        {
          key: 'lastBudget',
          type: 'custom',
          span: 24,
          render: <MoneyTable data={detail} />,
        },
      ],
    },
    {
      title: '本年资金预算',
      list: [
        {
          key: 'fundSource',
          type: 'custom',
          span: 24,
          rules: [{ required: true }],
          render: <CapitalSource readOnly={readOnly} />,
        },
      ],
    },
    {
      title: '其他信息',
      list: [
        {
          key: 'person',
          type: 'input',
          label: '项目负责人',
          rules: [{ required: true }],
          span: 12,
        },
        {
          key: 'contact',
          type: 'input',
          label: '联系电话',
          rules: [{ required: true }],
          span: 12,
        },
        {
          key: 'remark',
          type: 'textarea',
          label: '备注',
          span: 24,
        },
        {
          key: 'createTime',
          type: 'text',
          label: '填报日期',
          span: 24,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '其他附件',
          span: 24,
        },
      ],
    },
  ];
  const filters2 = [
    {
      title: '基础信息',
      list: [
        {
          key: id ? 'name' : 'projectUuid',
          type: id ? 'text' : 'select',
          label: '项目名称',
          asyncopt: {
            url: '/api/budget/v1/project/query',
          },
          prop: {
            onChange: (uuid, data) => {
              console.log('uuid', uuid);
              projectChange(uuid, data);
            },
          },
          span: 12,
        },
        {
          key: 'no',
          type: 'text',
          label: '项目ID(代码)',
          span: 12,
        },
        {
          key: 'ownerOrgUnit',
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'buildType',
          type: 'text',
          label: '项目性质',
          span: 12,
        },
        {
          key: 'projectType',
          type: 'tabs',
          prop: {
            defaultActiveKey: '2',
            onChange: tabChange,
          },
          options: [
            {
              label: '预算填报',
              value: 1,
            },
            {
              label: '基本信息',
              value: 2,
            },
          ],
          span: 24,
        },
        {
          key: ['professionData', 'display'],
          type: 'text',
          label: '行业领域',
          span: 12,
        },
        {
          key: ['serviceTypeData', 'display'],
          type: 'text',
          label: '项目类型',
          span: 12,
        },
      ],
    },
    {
      title: '项目简介',
      list: [
        {
          key: 'description',
          type: 'textarea',
          label: '项目简介',
          prop: { readOnly: true },
          span: 24,
        },
        {
          key: 'examine',
          type: 'textarea',
          label: '考核',
          prop: { readOnly: true },
          span: 24,
        },
        {
          key: 'buildNesscessary',
          type: 'textarea',
          label: '建设必要性',
          prop: { readOnly: true },
          span: 24,
        },
        {
          key: 'buildTarget',
          type: 'textarea',
          label: '建设目标',
          prop: { readOnly: true },
          span: 24,
        },
        {
          key: 'survey',
          type: 'textarea',
          label: '调研情况',
          prop: { readOnly: true },
          span: 24,
        },
      ],
    },
    {
      title: '前期准备',
      list: [
        {
          key: 'formation',
          type: 'text',
          label: '规划编制',
          span: 12,
        },
        {
          key: 'authentication',
          type: 'text',
          label: '专家认证',
          span: 12,
        },
      ],
    },
    {
      title: '建设周期',
      list: [
        {
          key: 'startDate',
          type: 'text',
          label: '启动时间',
          span: 12,
        },
        {
          key: 'endDate',
          type: 'text',
          label: '预计完成时间',
          span: 12,
        },
      ],
    },
  ];
  const filters3 = [
    {
      title: '基础信息',
      list: [
        {
          key: id ? 'name' : 'projectUuid',
          type: id ? 'text' : 'select',
          label: '项目名称',
          asyncopt: {
            url: '/api/budget/v1/project/query',
          },
          prop: {
            onChange: (uuid, data) => {
              console.log('uuid', uuid);
              projectChange(uuid, data);
            },
          },
          span: 12,
        },
        {
          key: 'no',
          type: 'text',
          label: '项目ID(代码)',
          placeholder: '请输入姓名',
          span: 12,
        },
        {
          key: ['ownerOrgUnit', 'name'],
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'buildType',
          type: 'text',
          label: '项目性质',
          span: 12,
        },
        {
          key: ['professionData', 'display'],
          type: 'text',
          label: '行业领域',
          span: 12,
        },
        {
          key: ['serviceTypeData', 'display'],
          type: 'text',
          label: '项目类型',
          span: 12,
        },
      ],
    },
    {
      title: '项目简介',
      list: [
        {
          key: 'description',
          type: 'text',
          label: '项目简介',
          span: 24,
        },
        {
          key: 'totalInvestment',
          type: 'text',
          label: '建设总投资',
          span: 24,
        },
        {
          key: 'paperLimit',
          type: 'text',
          label: '合同期限',
          span: 24,
        },
        {
          key: 'paperAmount',
          type: 'text',
          label: '合同金额',
          span: 24,
        },
        {
          key: 'budgetYear',
          type: 'select',
          label: '预算年份',
          options: dict.yearList,
          prop: {
            onChange: yearSelect,
          },
          span: 24,
        },
      ],
    },
    {
      title: '上年资金使用情况',
      list: [
        {
          key: 'lastBudget',
          type: 'custom',
          span: 24,
          render: <MoneyTable data={detail} />,
        },
      ],
    },
    {
      title: '本年资金预算',
      list: [
        {
          key: 'fundSource',
          type: 'custom',
          span: 24,
          rules: [{ required: true }],
          render: <CapitalSource readOnly={readOnly} />,
        },
      ],
    },
    {
      title: '其他信息',
      list: [
        {
          key: 'person',
          type: 'input',
          label: '项目负责人',
          rules: [{ required: true }],
          span: 12,
        },
        {
          key: 'contact',
          type: 'input',
          label: '联系电话',
          rules: [{ required: true }],
          span: 12,
        },
        {
          key: 'remark',
          type: 'textarea',
          label: '备注',
          span: 24,
        },
        {
          key: 'createTime',
          type: 'text',
          label: '填报日期',
          span: 24,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '其他附件',
          span: 24,
        },
      ],
    },
  ];

  const preproccess = data => {
    const fileUuidList = data.fileList
      ? data.fileList.map(item => item.uuid)
      : [];
    return {
      ...data,
      fileUuidList,
      amount: parseFloat(data.amount),
    };
  };
  const handleResult = type => {
    if (!comment && !type) {
      message.error('拒绝时请输入审批意见');
      return;
    }
    if (!detail || !detail.approveResult) {
      return message.error('项目信息不正确');
    }
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/project/report/v1/moneyReport/approve',
        data: {
          projectType: 'PLAN',
          comment: comment,
          result: type,
          uuid: detail.approveResult.uuid,
        },
      },
    }).then(() => {
      message.success('审批成功');
      dispatch({ type: '$router/back' });
    });
  };
  return (
    <div>
      <EditTemplate
        filters={filters}
        initialValues={detail}
        updateUrl={saveUrl}
        readOnly={readOnly}
        preproccess={preproccess}
        footer={
          isApprove && (
            <Button type="primary" onClick={() => setshowModal(true)}>
              审批
            </Button>
          )
        }
      />

      <Modal
        title="审批意见"
        visible={showModal}
        okText="通过"
        cancelText="拒绝"
        onCancel={() => setshowModal(false)}
        footer={[
          <AuthButton
            key="back"
            onClick={() => handleResult(false)}
            role="examine_project_funding"
          >
            拒绝
          </AuthButton>,
          <AuthButton
            type="primary"
            onClick={() => handleResult(true)}
            role="examine_project_funding"
          >
            通过
          </AuthButton>,
        ]}
      >
        <TextArea
          placeholder="审批意见，拒绝时必填"
          value={comment}
          onChange={e => setcomment(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default connect((state: any) => state.base)(BuildEdit);
